<template>
  <div>
    <div class="transition-box">
      <el-divider v-if="!isDialog">修改账号密码</el-divider>
      <el-form
        :model="passwordForm"
        :rules="passwordRule"
        class="passwordForm"
        ref="passwordForm"
        label-width="120px"
        aria-autocomplete="false"
      >
        <el-form-item label="当前账号：" prop="name" v-if="isShowUser">
          <el-input type="text" v-model.trim="userAndName" disabled>{{
            userAndName
          }}</el-input>
        </el-form-item>
        <el-form-item label="旧密码：" prop="oldPass" v-if="!isDialog">
          <el-input
            type="password"
            v-model.trim="passwordForm.oldPass"
            placeholder="输入旧密码"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码：" prop="newPass">
          <el-input
            type="password"
            v-model.trim="passwordForm.newPass"
            show-password
            clearable
            placeholder="输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="">
          <div
            :class="[
              'pwStrength',
              {
                pwDefule: pwLevel === 'defule',
                pwStrong: pwLevel === 'strong',
                pwMedium: pwLevel === 'medium',
                pwWeak: pwLevel === 'weak',
              },
            ]"
          >
            <div class="pwTxt clearfix">
              <span>弱</span>
              <span>中</span>
              <span>强</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="确认新密码：" prop="checkPass">
          <el-input
            type="password"
            v-model.trim="passwordForm.checkPass"
            show-password
            clearable
            placeholder="输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item v-show="!isDialog" style="margin-top: 40px">
          <el-button
            type="primary"
            size="medium"
            style="margin-left: 47px"
            class="saveBtn commonBut"
            @click="submitPassForm()"
            :loading="canSubmit"
            >保存修改</el-button
          >
          <el-button
            size="medium"
            class="cancelBtn"
            @click="cancelSubmit('passwordForm')"
            >取消</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'changePassword',
  props: {
    // loginType  isShowUserName
    isDialog: {
      type: Boolean,
      default: false,
    }, //是否是弹窗
    isFindPW: {
      type: Boolean,
      default: false,
    }, //是否是忘记密码
    isShowUser: {
      type: Boolean,
      default: false,
    }, //是否是忘记密码
  },
  data() {
    var validateOldPass = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('旧密码不能为空'))
      } else {
        var data = {}
        var url = ''
        if (localStorage.getItem('loginType') == 'DT') {
          url = 'api-m/inputUser/base/v1/validPassword'
          data = {
            id: this.$store.state.userId, //----用户id
            password: value,
          }
        } else {
          url = 'api-u/validpassword'
          data = {
            password: value,
          }
        }
        this.axios({
          method: 'post',
          url,
          data,
        }).then(
          (res) => {
            if (!res.data.hasError) {
              callback()
            } else {
              callback(new Error(res.data.errorMsg))
            }
          },
          (response) => {
            callback(new Error('验证旧密码失败'))
          }
        )
      }
    }
    //验证密码
    var validatePass1 = (rule, value, callback) => {
      var strongRegex = new RegExp(
        '^(?=.{8,})((?=.*[A-Z])|(?=.*[a-z]))(?=.*[0-9])(?=.*\\W).*$',
        'g'
      )
      var whstrongRegex = new RegExp(
        '^(?=.{11,})((?=.*[A-Z])|(?=.*[a-z]))(?=.*[0-9])(?=.*\\W).*$',
        'g'
      )
      var mediumRegex = new RegExp(
        '^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[0-9])(?=.*\\W))|((?=.*[a-z])(?=.*\\W))|((?=.*[A-Z])(?=.*\\W))).*$',
        'g'
      )
      var enoughRegex = new RegExp('(?=.{7,}).*', 'g')
      var Regex = new RegExp(/^[^\u4e00-\u9fa5]{0,}$/)
      var regEmpty = new RegExp(/\s+/g)
      var symbolsRegex = new RegExp(/^[^']*$/)

      var reg = /^[\?%#$@!^*,.;~<>/:&=\-_]+$/
      console.log(this.isWhUser())
      if (!this.isWhUser()) {
        if (value === '') {
          callback(new Error('新密码不能为空'))
          // }else if( !Regex.test(value) || !regEmpty.test(value)){
        } else if (
          !Regex.test(value) ||
          regEmpty.test(value) ||
          !symbolsRegex.test(value)
        ) {
          this.pwLevel = 'defule'
          callback(new Error('不允许输入汉字,空格,单引号'))
        } else {
          if (false == enoughRegex.test(value)) {
            // this.pwLevel = "defule";
            this.pwLevel = 'weak'
            callback(new Error('密码过于简单，请重新输入'))
            // callback();
            //密码小于六位的时候，密码强度图片都为灰色
          } else if (strongRegex.test(value)) {
            this.pwLevel = 'strong'
            callback()
            //密码为八位及以上并且字母数字特殊字符三项都包括,强度最强
          } else if (mediumRegex.test(value)) {
            this.pwLevel = 'medium'
            callback()
            //密码为七位及以上并且字母、数字、特殊字符三项中有两项，强度是中等
          } else {
            // 弱
            this.pwLevel = 'weak'
            callback(new Error('密码过于简单，请重新输入'))
            // callback();
            //如果密码为6为及以下，就算字母、数字、特殊字符三项都包括，强度也是弱的
          }
        }
      } else {
        if (value === '') {
          callback(new Error('新密码不能为空'))
          // }else if( !Regex.test(value) || !regEmpty.test(value)){
        } else if (
          !Regex.test(value) ||
          regEmpty.test(value) ||
          !symbolsRegex.test(value)
        ) {
          this.pwLevel = 'defule'
          callback(new Error('不允许输入汉字,空格,单引号'))
        } else {
          if (false == enoughRegex.test(value)) {
            // this.pwLevel = "defule";
            this.pwLevel = 'weak'
            callback(new Error('密码过于简单，请重新输入'))
            // callback();
            //密码小于六位的时候，密码强度图片都为灰色
          } else if (whstrongRegex.test(value)) {
            this.pwLevel = 'strong'
            callback()
            //密码为八位及以上并且字母数字特殊字符三项都包括,强度最强
          } else if (mediumRegex.test(value)) {
            this.pwLevel = 'medium'
            callback(new Error('密码过于简单，请重新输入'))
            //密码为七位及以上并且字母、数字、特殊字符三项中有两项，强度是中等
          } else {
            // 弱
            this.pwLevel = 'weak'
            callback(new Error('密码过于简单，请重新输入'))
            // callback();
            //如果密码为6为及以下，就算字母、数字、特殊字符三项都包括，强度也是弱的
          }
        }
      }
    }
    var validatePass2 = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('确认密码不能为空'))
      } else {
        if (value != this.passwordForm.newPass.replace(/\s+/g, '')) {
          callback(new Error('两次密码输入不一致'))
        }
        callback()
      }
    }
    //验证短信验证码
    var validateVsode = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('验证码不能为空'))
      } else {
        var url = 'api-bs/message/base/checkvc'
        var data = {
          tel: this.telphone,
          vc: this.telForm.vscode,
        }
        this.axios({
          method: 'post',
          url: url,
          data: data,
        }).then(
          (res) => {
            if (!res.data.hasError) {
              callback()
            } else {
              callback(new Error(res.data.errorMsg))
            }
          },
          (response) => {
            callback(new Error('验证失败'))
          }
        )
      }
    }
    return {
      //   updatePass: false,
      userAndName: '',
      canSubmit: false, //是否可以提交
      passwordRule: {
        oldPass: [
          { required: true, validator: validateOldPass, trigger: 'blur' },
        ],
        newPass: [
          { required: true, validator: validatePass1, trigger: 'blur' },
        ],
        checkPass: [
          { required: true, validator: validatePass2, trigger: 'blur' },
        ],
      },
      passwordForm: {
        oldPass: '',
        newPass: '',
        checkPass: '',
      },
      isShowUpdate: true,
      pwLevel: '', //密码强度
      loginType: '',
      // isDialog:true
    }
  },
  watch: {
    $route(to, from) {
      //   this.showForm();
      //获取页面信息
      //   this.getInfo();
    },
  },
  created() {
    //判断用户类型
    this.loginType = localStorage.getItem('loginType')

    // if(this.loginType === 'QY'){
    //     this.showQy = true;
    // }else{
    //     this.showQy = false;
    // };

    // this.showForm();

    //获取页面信息
    if (!this.isFindPW) {
      //   this.getInfo();
    }

    // this.isShowUpdate = this.$store.state.buttonLimitsArr.indexOf('myaccount:update') > -1;
    //未脱敏手机号

    this.telphone = this.$store.state.userTel
    //脱敏手机号
    if (this.telphone) {
      this.phone =
        this.telphone.substring(0, 3) +
        '****' +
        this.telphone.substring(this.telphone.length - 4)
    }
    this.userAndName = this.$store.state.usernameAndType
  },
  methods: {
    //根据修改类型显示不同的修改表单
    // showForm() {
    //   this.type = this.$route.query.type;
    //   if (this.type === "tel") {
    //     this.updatePass = false;
    //     this.updateTel = true;
    //   }
    //   if (this.type === "password") {
    //     this.updatePass = true;
    //     this.updateTel = false;
    //   }
    // },
    //修改密码
    // updatePassword() {
    //   this.updatePass = true;
    //   this.updateTel = false;
    //   this.canSubmit = false;
    //   this.$nextTick(function () {
    //     this.$refs.passwordForm.resetFields();
    //   });
    // },
    //获取页面信息
    getInfo() {
      let vm = this
      vm.axios({
        method: 'post',
        url: 'api-u/useraccount',
      })
        .then(
          (res) => {
            if (!res.data.hasError) {
              var data = res.data.result
              vm.userName = data.username
              vm.companyName = data.nickname
              vm.telphone = data.tel
              vm.userAndName = vm.userName + '(' + vm.companyName + ')'
              var tel =
                vm.telphone.substring(0, 3) +
                '****' +
                vm.telphone.substring(vm.telphone.length - 4)
              vm.phone = tel
            }
          },
          (response) => {
            this.$message({
              showClose: true,
              duration: 0,
              message: '获取账号信息失败',
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    },

    //密码修改成功后自动退出该账号并跳转至登录页面；
    logout() {
      var vm = this
      vm.axios({
        method: 'get',
        url:
          'api-u/sys/logout?Authorization=' +
          localStorage.getItem('access_token'),
      })
        .then(
          (res) => {
            //清除token
            localStorage.setItem('access_token', '')
            localStorage.setItem('refresh_token', '')
            localStorage.setItem('userName', '')
            vm.$router.replace('/login/loginNext?type=' + this.loginType)
          },
          (res) => {
            localStorage.setItem('access_token', '')
            localStorage.setItem('refresh_token', '')
            localStorage.setItem('userName', '')
            vm.$router.replace('/login/loginNext?type=' + this.loginType)
          }
        )
        .catch((error) => {})
    },
    //修改密码保存
    submitPassForm() {
      let vm = this
      vm.canSubmit = true
      var data = {}
      var url = ''
      // 接口平台
      if (localStorage.getItem('loginType') == 'DT') {
        url = 'api-m/inputUser/base/v1/updatePassword'
        data = {
          id: this.$store.state.userId, //----用户id
          password: vm.passwordForm.newPass,
        }
      } else {
        url = 'api-u/users/editpassword'
        data = {
          password: vm.passwordForm.newPass,
        }
      }
      vm.$refs['passwordForm'].validate((valid) => {
        if (valid) {
          if (this.isFindPW) {
            this.$emit('toFindPw', vm.passwordForm.newPass)
            vm.canSubmit = false
            return
          }
          vm.axios({
            method: 'post',
            url,
            data,
          })
            .then(
              (res) => {
                localStorage.setItem('pwIsStrong', true)
                if (this.isDialog) {
                  //弹窗，关闭弹窗
                  this.$message({
                    showClose: true,
                    message: '修改成功',
                    type: 'success',
                  })
                  this.$emit('colseChangePwDialog', '')
                } else {
                  this.$message({
                    showClose: true,
                    message: '密码修改成功,请重新登录',
                    type: 'success',
                  })
                  this.logout()
                }
                vm.canSubmit = false
              },
              (response) => {
                this.$message({
                  showClose: true,
                  duration: 0,
                  message: '修改失败',
                  type: 'error',
                })
                vm.canSubmit = false
              }
            )
            .catch((error) => {
              vm.canSubmit = false
            })
        } else {
          vm.canSubmit = false
          return false
        }
      })
    },
    //取消修改
    cancelSubmit(formName) {
      this.$emit('cancelSubmitChange', '')
      this.updatePass = false

      // 取消
      this.$refs[formName].resetFields()
    },
  },
}
</script>

<style lang="less" scoped>
.container {
  // position: absolute;
  // padding: 24px;
  // top: 106px;
  // bottom: 0px;
  // left: 0px;
  // right: 0px;
  // overflow-y: auto;
  // overflow-x: hidden;
  .blockTitle {
    height: 66px;
    line-height: 46px;
    padding: 10px 24px;
    background-color: #e4ebf1;
    font-size: 18px;
    font-weight: bold;
  }
  .passwordForm,
  .telForm {
    transform: translateX(-60px);
    width: 500px;
    margin: 50px auto;
    transform: translateX(-60px);
    .vscodeInput {
      .el-input {
        width: 220px;
        margin-right: 10px;
      }
    }
    // .getCode{
    //     color: #009588;
    //     background-color: #DEF7F3!important;
    //     border-color: #009588;
    // }
    // .getCode:hover{
    //     color: #fff;
    //     background-color: #009588!important;
    // }
  }
  .btnBox {
    text-align: center;
  }
  .updateItem {
    width: 108px;
    height: 36px;
    text-align: center;
    color: #fff;
    font: bold 14px/36px Microsoft YaHei;
    background-color: #02a2aa;
  }
  .backYellow {
    background-color: #f9a243;
  }
  .itemBox {
    padding-left: 24px;
    margin-top: 20px;
    .itemValue {
      color: #222;
    }
  }
}

// 密码强度样式
.pwStrength {
  width: 100%;
  background: #f5f5f5;
  box-shadow: inset 1px 1px 2px 0 rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  border-radius: 4px;
  padding: 4px;
  .pwTxt {
    width: 100%;
    height: 20px;
    line-height: 20px;
    color: #fff;
    text-align: center;
    border-radius: 2px;
    span {
      float: left;
      width: 33.3%;
      background-image: linear-gradient(180deg, #ebebed 0%, #d5d5d6 100%);
      &:nth-of-type(1) {
        border-radius: 2px 0 0 2px;
        border-right: 2px solid #fff;
      }
      &:nth-of-type(3) {
        border-radius: 0 2px 2px 0;
        border-left: 2px solid #fff;
      }
    }
  }
}

.pwDefule .pwTxt {
  span {
    background-image: linear-gradient(180deg, #ebebed 0%, #d5d5d6 100%);
  }
}

.pwMedium .pwTxt {
  span:nth-of-type(1) {
    background-image: linear-gradient(180deg, #f7915e 0%, #ed5830 100%);
  }
  span:nth-of-type(2) {
    background-image: linear-gradient(180deg, #fdcf7e 0%, #ff8c00 100%);
  }
}
.pwStrong .pwTxt {
  span:nth-of-type(1) {
    background-image: linear-gradient(180deg, #f7915e 0%, #ed5830 100%);
  }
  span:nth-of-type(2) {
    background-image: linear-gradient(180deg, #fdcf7e 0%, #ff8c00 100%);
  }
  span:nth-of-type(3) {
    background-image: linear-gradient(180deg, #5ab655 0%, #12800c 100%);
  }
}
.pwWeak .pwTxt {
  span:nth-of-type(1) {
    background-image: linear-gradient(180deg, #f7915e 0%, #ed5830 100%);
  }
}
/deep/.el-divider {
  background-color: rgba(220, 223, 230, 0.4) !important;
}
</style>
